/*
 * @Author: RidingWind
 * @Date: 2018-02-27 10:00:47
 * @Last Modified by: 大招科技 - RidingWind
 * @Last Modified time: 2018-02-27 17:59:42
 */
/* eslint-disable */
import $ from 'jquery';
import baseUri from './baseUri';
import TOAST from './toast';

function checkStatus(response) {
  return response;
}

function makeParams(params) {
  let result = '';

  for (const i in params) {
    result += `${i}=${encodeURIComponent(params[i])}&`;
  }
  
  return result;
}

const ajax = (url, type = 'GET', data = {}, timeout = 3000) => {
  const options = {
    url: `${baseUri}${url}`,
    type,
    data: makeParams(data),
    processData: false,
    contentType: 'application/x-www-form-urlencoded;',
    timeout,
  };

  $.support.cors = true;
  const req = $.ajax(options);

  return req.then(checkStatus)
    .fail((error) => {
      if (error) {
        // TODO, show error
        TOAST.show(error);
      }
      console.log('request error', error);
    });
};

export default ajax;
